package com.cloudweb.oa.controller;

import cn.js.fan.util.ParamUtil;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.vo.Result;
import com.redmoon.oa.dept.DeptDb;
import com.redmoon.oa.dept.DeptUserDb;
import com.redmoon.oa.flow.FormDb;
import com.redmoon.oa.flow.FormField;
import com.redmoon.oa.person.UserDb;
import com.redmoon.oa.person.UserMgr;
import com.redmoon.oa.pvg.Privilege;
import com.redmoon.oa.sys.DebugUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Vector;

@Controller
public class DeptSelectCtlController {

    @Autowired
    HttpServletRequest request;

    @RequestMapping(value="/flow/macro/macroJsDeptSelectCtl", method = RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    public String macroJsDeptSelectCtl(Model model) {
        String deptField = ParamUtil.get(request, "deptField");
        // 联动字段{user}，部门变化，user字段列出该部门中的用户
        String userField = ParamUtil.get(request, "userField");
        // 联动字段@user，用户变化，deptField中显示其所在部门
        String atUserField = ParamUtil.get(request, "atUserField");
        // 联动字段&dept，部门变化，联动显示其父级部门
        String parentDeptField = ParamUtil.get(request, "parentDeptField");
        String formCode = ParamUtil.get(request, "formCode");
        String op = ParamUtil.get(request, "op");

        model.addAttribute("op", op);
        model.addAttribute("formCode", formCode);
        model.addAttribute("deptField", deptField);
        model.addAttribute("userField", userField);
        model.addAttribute("atUserField", atUserField);
        model.addAttribute("parentDeptField", parentDeptField);

        return "th/flow/macro/macro_js_dept_select_ctl";
    }

    @RequestMapping(value="/flow/macro/getUserListOptions", method = RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
    public Result<Object> getUserListOptions() {
        JSONObject json = new JSONObject();
        Privilege privilege = new Privilege();

        String deptField = ParamUtil.get(request, "deptField");
        // 联动字段{user}，部门变化，user字段列出该部门中的用户
        String userField = ParamUtil.get(request, "userField");
        String formCode = ParamUtil.get(request, "formCode");
        String deptCode = ParamUtil.get(request, "deptCode");
        if ("".equals(deptCode)) {
            return new Result<>(json);
        }

        boolean isBlank = false;
        boolean allUserInChildren = false; // 关联用户列表宏控件显示所有的用户（含子部门）

        if (!"".equals(formCode) && !"".equals(userField)) { // 向下兼容
            FormDb fd = new FormDb();
            fd = fd.getFormDb(formCode);
            if (!fd.isLoaded()) {
                return new Result<>(false, "表单: " + formCode + " 不存在");
            }

            FormField ffDept = fd.getFormField(deptField);
            if (ffDept != null) {
                String desc = ffDept.getDescription();
                String[] descAry = StrUtil.split(desc, ",");
                if (descAry != null) {
                    for (String s : descAry) {
                        if ("allUserInChildren".equals(s.trim())) {
                            allUserInChildren = true;
                            break;
                        }
                    }
                }
            }

            FormField ff = fd.getFormField(userField);
            if (ff != null) {
                String desc = ff.getDescription();
                if ("".equals(desc)) {
                    desc = ff.getDefaultValueRaw();
                }
                String[] descAry = StrUtil.split(desc, ",");
                if (descAry != null) {
                    for (String s : descAry) {
                        if ("isBlank".equalsIgnoreCase(s.trim())) {
                            isBlank = true;
                            break;
                        }
                    }
                }
            } else {
                DebugUtil.i(getClass(), "getUserListOptions", "表单:" + formCode + "中的字段" + userField + "不存在");
            }
        }

        UserMgr um = new UserMgr();
        DeptUserDb dud = new DeptUserDb();
        String userName = privilege.getUser(request);
        if (userName == null || "".equals(userName)) {
            return new Result<>(false, "userName 不能为空");
        }

        StringBuilder sb = new StringBuilder();
        sb.append("<option value=''>无</option>");

        Vector<DeptUserDb> v;
        if (allUserInChildren) {
            v = dud.listAll(deptCode);
        } else {
            v = dud.list(deptCode);
        }

        for (DeptUserDb deptUserDb : v) {
            dud = deptUserDb;
            UserDb ud = um.getUserDb(dud.getUserName());
            if (!isBlank) {
                if (userName.equals(ud.getName())) {
                    sb.append("<option selected value='" + ud.getName() + "'>" + ud.getRealName() + "</option>");
                } else {
                    sb.append("<option value='" + ud.getName() + "'>" + ud.getRealName() + "</option>");
                }
            } else {
                sb.append("<option value='" + ud.getName() + "'>" + ud.getRealName() + "</option>");
            }
        }
        json.put("options", sb.toString());
        return new Result<>(json);
    }

    @RequestMapping(value="/flow/macro/getParentDept", method = RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
    public Result<Object> getParentDept() {
        JSONObject json = new JSONObject();
        String deptCode = ParamUtil.get(request, "deptCode");
        if ("".equals(deptCode)) {
            return new Result<>(json);
        }

        DeptDb dd = new DeptDb();
        dd = dd.getDeptDb(deptCode);
        if (DeptDb.ROOTCODE.equals(dd.getCode())) {
            json.put("parentCode", DeptDb.ROOTCODE);
        } else {
            json.put("parentCode", dd.getParentCode());
        }
        return new Result<>(json);
    }

    @RequestMapping(value="/flow/macro/getUserDept", method = RequestMethod.POST, produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
    @ResponseBody
    public Result<Object> getUserDept() {
        String formCode = ParamUtil.get(request, "formCode");
        String deptField = ParamUtil.get(request, "deptField");

        JSONObject json = new JSONObject();
        FormDb fd = new FormDb();
        fd = fd.getFormDb(formCode);
        FormField ff = fd.getFormField(deptField);
        // 判断是否仅取子单位
        String defaultValue = StrUtil.getNullStr(ff.getDescription());
        String[] defaultArr = defaultValue.split(",");
        boolean isUnit = false;
        for(String defaultDept : defaultArr) {
            if(defaultDept.length() > 0) {
                if ("unit".equals(defaultValue)) {
                    isUnit = true;
                    break;
                }
            }
        }

        DeptUserDb dud = new DeptUserDb();
        String atUser = ParamUtil.get(request, "atUser");
        if (isUnit) {
            DeptDb dd = dud.getUnitOfUser(atUser);
            json.put("res", 0);
            json.put("deptCode", dd.getCode());
        } else {
            Vector<DeptDb> v = dud.getDeptsOfUser(atUser);
            if (v.size() > 0) {
                json.put("res", 0);
                json.put("deptCode", v.elementAt(0).getCode());
            } else {
                json.put("res", 1);
            }
        }
        return new Result<>(json);
    }
}
